package tr.edu.yildiz.ce.app_manager.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tr.edu.yildiz.ce.app_manager.dao.ApplicationDao;
import tr.edu.yildiz.ce.app_manager.dao.ProxyDao;
import tr.edu.yildiz.ce.app_manager.model.AppProxy;
import tr.edu.yildiz.ce.app_manager.model.Application;
import tr.edu.yildiz.ce.app_manager.model.gen.ApplicationList;
import tr.edu.yildiz.ce.app_manager.service.ApplicationManagerService;

@Service
@Transactional
public class ApplicationManagerServiceImpl implements ApplicationManagerService {

	@Autowired
	ProxyDao proxyDao;
	
	
	@Override
	public ApplicationList listAvailableApps(String username,String password) {
		AppProxy proxy = proxyDao.findByUsernameAndPassword(username, password);
		if (proxy == null)
			throw new RuntimeException("Login fault");
		ApplicationList applicationList = new ApplicationList();
		fillApplications(proxy, applicationList);
		return applicationList;
	}
	
	private void fillApplications(AppProxy proxy,ApplicationList applicationList){
		Set<Application> applicationSet = proxy.getApplications();
		for (Application application : applicationSet) {
			tr.edu.yildiz.ce.app_manager.model.gen.Application app = new tr.edu.yildiz.ce.app_manager.model.gen.Application();
			app.setName(application.getApplicationName());
			app.setVersion(application.getApplicationVersion());
			app.setUrl("http://localhost:9080/app-manager/dl/downloadServlet?applicationId=" + application.getApplicationId());
			app.setAutoDeploy(application.isAutoDeploy());
			applicationList.getApplication().add(app);
		}
		if (proxy.getParent() != null)
			fillApplications(proxy.getParent(), applicationList);
	}

}
